package com.lindroy.viewpagerfragmentpractice

import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentPagerAdapter
import com.lindroy.viewpagerfragmentpractice.fragment.AFragment
import com.lindroy.viewpagerfragmentpractice.fragment.BFragment
import com.lindroy.viewpagerfragmentpractice.fragment.BaseFragment
import kotlinx.android.synthetic.main.activity_sample2.*
import kotlinx.android.synthetic.main.activity_sample2.button
import kotlinx.android.synthetic.main.activity_sample2.viewPager
import kotlinx.android.synthetic.main.activity_view_pager2.*

class SampleActivity2 : AppCompatActivity() {

    private val fragmentTags = listOf<String>(
        AFragment::class.java.simpleName,
        BFragment::class.java.simpleName
    )

    private val fragments = SparseArray<BaseFragment>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample2)
        viewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
            override fun getCount() = fragmentTags.size

            override fun getItem(position: Int) = when (fragmentTags[position]) {
                AFragment::class.java.simpleName -> AFragment()
                BFragment::class.java.simpleName -> BFragment()
                else -> AFragment()
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                fragments.put(position,(super.instantiateItem(container, position) as BaseFragment))
                return fragments[position]
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                super.destroyItem(container, position, `object`)
                fragments.removeAt(position)
            }
        }

        button.setOnClickListener {
            fragments[viewPager.currentItem]?.showMessage("hello")
        }
    }
}